package com.hmall.item.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.item.config.MqConfiguration;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.ItemDoc;
import com.hmall.item.service.IItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RequiredArgsConstructor
@Slf4j
public class MqListener {

    private final IItemService itemService;

    private final RestHighLevelClient restHighLevelClient;

    /**
     * 商品插入和更新队列监听器
     */
    @RabbitListener(queues = MqConfiguration.ITEM_INSERT_QUEUE)
    public void itemInsertAndUpdateQueueListener(Long itemId){
        try {
            Item item = itemService.getById(itemId);
            ItemDoc itemDoc = new ItemDoc(item);
            IndexRequest indexRequest = new IndexRequest("item").id(String.valueOf(itemId));
            indexRequest.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("ES商品插入或更新失败");
            throw new RuntimeException(e);
        }
    }

    @RabbitListener(queues = MqConfiguration.ITEM_DELETE_QUEUE)
    public void itemDeleteQueueListener(Long itemId){
        try {
            DeleteRequest deleteRequest = new DeleteRequest("item").id(String.valueOf(itemId));
            restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("ES商品删除失败");
            throw new RuntimeException(e);
        }
    }
}
